﻿using System;
using System.IO.Pipes;
using System.Text;

namespace ConsoleAppNamedPipeTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                new PipeServer();
            }
            Console.WriteLine("Press <Enter> to terminate this server application.");
            Console.ReadLine();
        }
    }

    internal class PipeServer
    {
        private readonly NamedPipeServerStream m_pipe = new NamedPipeServerStream("Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

        public PipeServer()
        {
            m_pipe.BeginWaitForConnection(ClientConnected, null);
        }

        private void ClientConnected(IAsyncResult ar)
        {
            new PipeServer();
            m_pipe.EndWaitForConnection(ar);
            byte[] data = new byte[1000];
            m_pipe.BeginRead(data, 0, data.Length, GotRequest, data);
        }

        private void GotRequest(IAsyncResult ar)
        {
            int bytesRead = m_pipe.EndRead(ar);
            byte[] data = (Byte[])ar.AsyncState;
            data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray());
            m_pipe.BeginWrite(data, 0, data.Length, WriteDone, null);
        }

        private void WriteDone(IAsyncResult ar)
        {
            m_pipe.EndWrite(ar);
            m_pipe.Close();
        }
    }
}